package com.fmboy.MXH.nav.service.impl;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class EmailService {

    private static final ConcurrentHashMap<String, CaptchaInfo> captchaCache = new ConcurrentHashMap<>();

    @Value("${mxh.email.time}")
    private int CAPTCHA_EXPIRATION_MINUTES;

    @Value("${mxh.email.host}")
    private String host;

    @Value("${mxh.email.port}")
    private int port;

    @Value("${mxh.email.username}")
    private String username;

    @Value("${mxh.email.password}")
    private String password;

    @Value("${mxh.email.auth}")
    private String auth;

    @Value("${mxh.email.starttls.enable}")
    private String starttlsEnable;

    /**
     * 验证提供的验证码是否匹配并且未过期。
     *
     * @param email        用户邮箱地址
     * @param inputCaptcha 用户输入的验证码
     * @return 如果验证码有效且未过期则返回 true，否则返回 false
     */
    public static boolean verifyCaptcha(String email, String inputCaptcha) {
        CaptchaInfo captchaInfo = captchaCache.get(email);

        // 检查验证码是否存在
        if (captchaInfo == null) {
            return false;
        }

        // 检查验证码是否匹配
        if (!inputCaptcha.equals(captchaInfo.getCaptcha())) {
            return false;
        }

        // 检查验证码是否已过期
        LocalDateTime now = LocalDateTime.now();
        return !captchaInfo.getExpirationTime().isBefore(now);
    }

    //删除验证码
    public static void deleteCaptcha(String email) {
        captchaCache.remove(email);
    }

    public void sendVerificationEmail(String to) throws MessagingException {
        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", auth);
        properties.put("mail.smtp.starttls.enable", starttlsEnable); // 启用 STARTTLS 加密

        // 创建会话并验证身份
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // 生成验证码
        String captcha = generateCaptcha();
        // 将验证码存储到缓存中，设置过期时间
        cacheCaptcha(to, captcha);

        // 创建邮件对象
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username)); // 设置发件人
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // 设置收件人
        message.setSubject("喵星汇-导航 - 验证码通知"); // 设置邮件主题

        // 构建HTML内容，包含验证码
        String htmlContent = buildHtmlWithCaptcha(captcha, to);
        message.setContent(htmlContent, "text/html; charset=utf-8");

        // 发送邮件
        Transport.send(message);
    }

    private String generateCaptcha() {
        SecureRandom random = new SecureRandom();
        return String.format("%06d", random.nextInt(999999)); // 生成6位数字验证码
    }

    private void cacheCaptcha(String email, String captcha) {
        LocalDateTime expirationTime = LocalDateTime.now().plusMinutes(CAPTCHA_EXPIRATION_MINUTES);
        captchaCache.put(email, new CaptchaInfo(captcha, expirationTime));
    }

    private String buildHtmlWithCaptcha(String captcha, String to) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        return "<div style=\"margin: auto;padding: 20px;max-width: 500px;text-align: center;border: 1px solid #ccc;border-top: 5px solid #9373EE;border-radius: 8px;\">" +
                "  <h2 style=\"font-size: 24px;font-weight: bold;\">喵星汇-导航</h2>" +
                "  <p style=\"margin: 0;color: #555;font-size: 18px;\">尊敬的 <strong>" + to + "</strong> 用户 您好！</p>" +
                "  <p style=\"margin: 0;color: #555;font-size: 16px;\">您正在进行邮箱验证操作，验证码为:</p>" +
                "  <p style=\"margin: 0;padding: 16px;color: #9373EE;font-size: 20px;font-weight: bold;background-color: #9373EE10;border-radius: 5px;\">" + captcha + "</p>" +
                "  <p style=\"margin: 0;color: #1c1c1c90;font-size: 14px;\">此验证码 5 分钟内有效</p>" +
                "  <p style=\"margin: 0;color: #1c1c1c90;font-size: 14px;\">如非本人操作</p>" +
                "  <p style=\"margin: 0;color: #1c1c1c90;font-size: 14px;\">转给他人将导致账号被盗和个人信息泄漏，谨防诈骗</p>" +
                "  <p style=\"margin: 0;text-align: right;\"><a href=\"https://mxh.fmboy.com\" target=\"_blank\" style=\"color: #9373EE;text-decoration: none;font-weight: bold;\">喵星汇</a></p>" +
                "  <p style=\"margin: 0;text-align: right;color: #555;font-size: 12px;\">" + currentTime.format(formatter) + "</p>" +
                "</div>";
    }

    // 内部类用于存储验证码和其过期时间
    private static class CaptchaInfo {
        private final String captcha;
        private final LocalDateTime expirationTime;

        public CaptchaInfo(String captcha, LocalDateTime expirationTime) {
            this.captcha = captcha;
            this.expirationTime = expirationTime;
        }

        public String getCaptcha() {
            return captcha;
        }

        public LocalDateTime getExpirationTime() {
            return expirationTime;
        }
    }
}